<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Created by lni_wang.
 * Product: PhpStorm
 * Date: 2017/4/5 14:00
 * File: Oauth.php
 */
class Oauth extends MY_Controller
{
    /**
     * 获得授权码
     * @http get
     * @params
     *  app_id      客户端编号
     * @return
     *  code        授权码
     */
    public function authorize_get()
    {
        try{
            $params = $this->get();
            data_picker($params, [
                'app_id',
            ]);

            $this->load->model('Oauth_model');
            $this->set_response_by_data($this->Oauth_model->get_code($params));
        }catch (SysException $e){
            $this->set_response_by_SysException($e);
        }catch(Exception $e){
            $this->set_response_by_exception($e);
        }
    }

    /**
     *  获得 accessToken
     * @http post
     * @params post
     *  code            授权码
     *  app_secret      客户端凭证
     * @return
     *  access_token                access_token编号
     *  expires_in                  access_token编号 到期时间
     *  refresh_token               access_token刷新用的 refresh_token
     */
    public function access_token_post()
    {
        try{
            $params = $this->post();
            data_picker($params, [
                'code',
                'app_secret',
            ]);

            $this->load->model('Oauth_model');
            if($params['code']){
                $result = $this->Oauth_model->get_access_token_by_code($params);
            }else{
                throw new SysException(30001);
            }

            $this->set_response_by_data($result);
        }catch (SysException $e){
            $this->set_response_by_SysException($e);
        }catch(Exception $e){
            $this->set_response_by_exception($e);
        }
    }

    /**
     * 刷新 access_token
     * @http post
     * @params
     *  refresh_token
     * @return
     *  access_token                access_token编号
     *  expires_in                  access_token编号 到期时间
     *  refresh_token               access_token刷新用的 refresh_token
     */
    public function refresh_token_post()
    {
        try{
            $params = $this->head();
            data_picker($params, [
                'refresh_token',
            ]);

            $this->load->model('Oauth_model');
            $this->set_response_by_data($this->Oauth_model->get_access_token_by_refresh_token($params));
        }catch (SysException $e){
            $this->set_response_by_SysException($e);
        }catch(Exception $e){
            $this->set_response_by_exception($e);
        }
    }
}